package com.financing.wap.web.controller.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.BankCardDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IBankCardService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

/**
 * 银行卡-Controller
 * 
 * @author lisu
 *
 */
@Controller("bankCardController")
@RequestMapping("/api/bankCard")
public class BankCardController extends BaseController {

	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IBankCardService bankCardServiceImpl;

	@Autowired
	private ICheckCodeService checkCodeServiceImpl;

	/**
	 * 获取登录人银行卡列表
	 * 
	 * @param bankCardDTO
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap queryList(BankCardDTO bankCardDTO) {
		ResultMap result = new ResultMap();

		logger.info("In BankCardController queryList Begin");

		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		bankCardDTO.setUserId(loginUser.getId());
		try {
			List<BankCardDTO> list = bankCardServiceImpl
					.queryBankCardList(bankCardDTO);

			// 账户名加密、卡号加密
			for (int i = 0; i < list.size(); i++) {
				BankCardDTO bean = list.get(i);
				if (bean == null) {
					continue;
				}
				bean.setCardNumber(StringUtil.encryptCardNumber(bean
						.getCardNumber()));
			}
			result.setAttribute("list", list);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("银行卡查询成功");
		} catch (Exception e) {
			logger.error("error BankCardController queryList:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("银行卡查询失败");
		}
		logger.info("In BankCardController queryList end");
		return result;
	}

	/**
	 * 添加收款账户信息
	 * @param request
	 * @param response
	 * @param verifyCode 验证码
	 * @param bankCardDTO 收款账户对象
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public ResultMap addBankCard(HttpServletRequest request,
			HttpServletResponse response, String vCode,
			BankCardDTO bankCardDTO) {
		ResultMap result = new ResultMap();

		logger.info("In BankCardController addBankCard Begin");

		// 初始化属性
		DTOdateSetUtil.setCreateInfo(bankCardDTO);
		DTOdateSetUtil.setUpdateInfo(bankCardDTO);
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		bankCardDTO.setUserId(loginUser.getId());
		String mobile = loginUser.getLoginName();

		// 添加参数验证 ，卡号、手机号、卡类型

		if (StringUtil.isNullOrEmptyStr(bankCardDTO.getBankType())
				|| StringUtil.isNullOrEmptyStr(bankCardDTO.getCardNumber())
				|| StringUtil.isNullOrEmptyStr(vCode)
				|| StringUtil.isNullOrEmptyStr(mobile)) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}
		// 不是支付宝 就要填写 账户名
		if (!Constants.BANK_CARD_TYPE_ZFB.equals(bankCardDTO.getBankType())
				&& StringUtil.isNullOrEmptyStr(bankCardDTO.getUserName())) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}

		// 校验验证码
		if (checkCodeServiceImpl.CheckCodeSwitch()) {
			ResultMap resultOtp = checkOtpCode(mobile, vCode);
			if (!STATUS.SUCCESS.equals(resultOtp.getStatus())) {
				result.setStatus(resultOtp.getStatus());
				result.setStatusCode(resultOtp.getStatusCode());
				result.setMessage(resultOtp.getMessage());
				return result;
			}
		}
		logger.info("In BankCardController check parameters success!");
		try {
			if (bankCardServiceImpl.checkBankType(bankCardDTO)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_CARD_TYPE_NOTONLY);
				result.setMessage("提现账户不允许重复添加");
				return result;
			}
			if (bankCardServiceImpl.checkBankName(bankCardDTO)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_CARD_UNMBER_NOTONLY);
				result.setMessage("提现账户卡号已经添加过");
				return result;
			}
			logger.info("In BankCardController check card notonly success!");
			bankCardServiceImpl.insertBankCard(bankCardDTO);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("error BankCardController addBankCard:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		logger.info("In BankCardController addBankCard end");
		return result;
	}

	public ResultMap deleteBankCard(BankCardDTO bankCardDTO) {
		ResultMap result = new ResultMap();

		logger.info("In BankCardController deleteBankCard Begin");

		// 初始化属性
		DTOdateSetUtil.setUpdateInfo(bankCardDTO);
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		bankCardDTO.setUserId(loginUser.getId());
		try {
			int influenceCount = bankCardServiceImpl
					.deleteBankCard(bankCardDTO);
			logger.info("In BankCardController deleteBankCard count=:"
					+ influenceCount);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("error BankCardController deleteBankCard:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		logger.info("In BankCardController deleteBankCard end");
		return result;
	}

	/**
	 * 修改收款账户
	 * @param request
	 * @param response
	 * @param verifyCode 验证码
	 * @param oldCardNumber 原账户
	 * @param bankCardDTO 收款账户对象
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public ResultMap updateBankCard(HttpServletRequest request,
			HttpServletResponse response, String vCode,
			String oldCardNumber, BankCardDTO bankCardDTO) {
		ResultMap result = new ResultMap();

		logger.info("In BankCardController updateBankCard Begin");

		// 初始化属性
		DTOdateSetUtil.setUpdateInfo(bankCardDTO);
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		bankCardDTO.setUserId(loginUser.getId());
		String mobile = loginUser.getLoginName();

		// 添加参数验证 ，卡号、手机号、卡类型 、原卡号 、银行卡id
		if (StringUtil.isNullOrEmptyStr(oldCardNumber)
				|| StringUtil.isNullOrEmptyStr(bankCardDTO.getBankType())
				|| StringUtil.isNullOrEmptyStr(bankCardDTO.getCardNumber())
				|| StringUtil.isNullOrEmptyStr(vCode)
				|| StringUtil.isNullOrEmptyStr(mobile)
				|| bankCardDTO.getId() == null) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}

		// 不是支付宝 就要填写 账户名
		if (!Constants.BANK_CARD_TYPE_ZFB.equals(bankCardDTO.getBankType())
				&& StringUtil.isNullOrEmptyStr(bankCardDTO.getUserName())) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("参数缺失");
			return result;
		}

		// 校验验证码
		if (checkCodeServiceImpl.CheckCodeSwitch()) {
			ResultMap resultOtp = checkOtpCode(mobile, vCode);
			if (!STATUS.SUCCESS.equals(resultOtp.getStatus())) {
				result.setStatus(resultOtp.getStatus());
				result.setStatusCode(resultOtp.getStatusCode());
				result.setMessage(resultOtp.getMessage());
				return result;
			}
		}
		logger.info("In BankCardController check parameters success!");
		try {

			BankCardDTO bankCardDTOview = bankCardServiceImpl
					.queryBankCard(bankCardDTO);
			if (!bankCardDTOview.getCardNumber().equals(oldCardNumber)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_CARD_UNMBER_ERROR);
				result.setMessage("输入原卡号错误");
				return result;
			}
			logger.info("In BankCardController check oldCardNumber success!");
			// 是支付宝类型就不能修改类型。是银行类型不能修改成支付宝类型
			if (Constants.BANK_CARD_TYPE_ZFB.equals(bankCardDTOview
					.getBankType())) {
				if (!bankCardDTO.getBankType().equals(
						bankCardDTOview.getBankType())) {
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
					return result;
				}
			} else {
				if (Constants.BANK_CARD_TYPE_ZFB.equals(bankCardDTO
						.getBankType())) {
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
					return result;
				}
			}
			//判断卡号的唯一
			if (bankCardServiceImpl.checkBankName(bankCardDTO)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_CARD_UNMBER_NOTONLY);
				result.setMessage("提现账户卡号已经添加过");
				return result;
			}
			//新卡号不能和久卡号一致
			if (bankCardDTOview.getCardNumber().equals(bankCardDTO.getCardNumber())) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_CARD_UNMBER_NOTONLY);
				return result;
			}
			logger.info("In BankCardController check BankType success!");
			bankCardServiceImpl.updateBankCard(bankCardDTO);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("error BankCardController updateBankCard:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		logger.info("In BankCardController updateBankCard end");
		return result;
	}

	/**收款账户查询信息
	 * @param bankCardId
	 * @return
	 */
	@RequestMapping("/view/{bankCardId}")
	@ResponseBody
	public ResultMap viewBankCardId(@PathVariable Integer bankCardId) {
		ResultMap result = new ResultMap();

		logger.info("In BankCardController viewBankCardId Begin");

		BankCardDTO bankCardDTO = new BankCardDTO();

		// 初始化属性
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		bankCardDTO.setUserId(loginUser.getId());
		bankCardDTO.setId(bankCardId);
		try {

			BankCardDTO bankCardDTOview = bankCardServiceImpl
					.queryBankCard(bankCardDTO);
			// 加密敏感数据
			if (bankCardDTOview != null) {
				bankCardDTOview.setCardNumber(StringUtil
						.encryptCardNumber(bankCardDTOview.getCardNumber()));
			}
			logger.info("In BankCardController viewBankCardId success");
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("dto", bankCardDTOview);
		} catch (Exception e) {
			logger.error("error BankCardController viewBankCardId:", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		logger.info("In BankCardController viewBankCardId end");
		return result;
	}
}
